import { ref, reactive } from 'vue';
import { registerApi } from '../apis/loginApi';

export default function useRegister() {
  const registerLodingRef = ref(false);
  const registerFormRef = ref(null);
  const registerForm = reactive({
    titleSrc: '',
    userName: '',
    passWord: '',
    nickName: '',
    sex: '3',
  });

  const validatorTitleSrc = (rule, value, callback) => {
    console.log(value);
    if (!value) {
      return callback(new Error('请上传头像！'));
    } else {
      callback();
    }
  };

  const registerRules = reactive({
    titleSrc: {
      required: true,
      validator: validatorTitleSrc,
    },
    userName: {
      required: true,
      message: '请输入用户名',
      trigger: 'change',
    },
    passWord: {
      required: true,
      message: '请输入密码',
      trigger: 'change',
    },
  });

  const registerResetForm = async (formEl) => {
    if (!formEl) return;
    await formEl.resetFields();
  };

  const registerSubmitForm = async (formEl, msg, back, isMobile) => {
    if (!formEl) return;
    !isMobile
      ? validatePc(formEl, msg, back)
      : validateMobile(formEl, msg, back, isMobile);
  };
  // 移动端校验
  const validateMobile = async (formEl, msg, back) => {
    const bool = await formEl.validate();
    if (bool) {
      registerSave(formEl, msg, back, true);
    }
  };
  // pc客户端校验
  const validatePc = (formEl, msg, back) => {
    formEl.validate((valid, fields) => {
      if (valid) {
        registerSave(formEl, msg, back);
      } else {
        console.log('error submit!', fields);
      }
    });
  };
  // 清空方法不一致 pc 和 移动端
  const reset = async (formEl, isMobile) => {
    if (!isMobile) {
      formEl.resetFields();
    } else {
      formEl.reset();
    }
    registerForm.titleSrc = '';
  };
  const registerSave = async (formEl, msg, back, isMobile) => {
    try {
      registerLodingRef.value = true;
      const res = await registerApi(registerForm);
      console.log(res);
      if (res.code === 200) {
        await msg({ type: 'success', message: '注册成功!' });
        await reset(formEl, isMobile);
        back('/login');
      }
    } catch (error) {
    } finally {
      registerLodingRef.value = false;
    }
  };

  return {
    registerLodingRef,
    registerFormRef,
    registerForm,
    registerRules,
    registerResetForm,
    registerSubmitForm,
  };
}
